class DesignerWorkItem < ActiveRecord::Base

  belongs_to :work_item
  belongs_to :designer
  belongs_to :stage
  belongs_to :work_item_type

  validates_presence_of :work_item_id,
    :designer_id,
    :billing_area,
    :work_load,
    :guided_percent,
    :provided_percent,
    :difficulty_num,
    :should_be_payed
  validates_uniqueness_of :work_item_id,
    :scope => :designer_id
  validates_numericality_of :billing_area,
    :greater_than_or_equal_to => 0
  validates_numericality_of :work_load,
    :greater_than_or_equal_to => 0
  validates_numericality_of :guided_percent,
    :greater_than_or_equal_to => 0
  validates_numericality_of :provided_percent,
    :greater_than_or_equal_to => 0
  validates_numericality_of :difficulty_num,
    :greater_than_or_equal_to => 0
  validates_numericality_of :type_num,
    :greater_than_or_equal_to => 0
  validates_numericality_of :motify_num,
    :greater_than_or_equal_to => 0

  def reset_should_be_payed!
    self.should_be_payed = work_item.pay_unit * (work_load * 0.01) * (guided_percent * 0.01) * (provided_percent * 0.01) * (difficulty_num * 0.01) *(type_num * 0.01)*(motify_num * 0.01)* billing_area if work_item
  end

  def self.paying_total_amount
    sum :should_be_payed,
      :conditions => [
        'stages.pay_status = ? ',
        'paying'
      ],
      :include => :stage
  end

  def before_save
    if work_item
      # stage & work_item_type
      self.work_item_type = work_item.work_item_type
      self.stage = work_item.stage
      # should_be_payed
      reset_should_be_payed!
    end
  end

  def after_save
    if stage
      # recomputing stage's stat
      stage.reset_should_be_payed!
      stage.save!
      # recomputing project's stat
      stage.project.reset_stat!
      stage.project.save!
    end
  end

  def after_destroy
    if stage
      # recomputing stage's stat
      stage.reset_should_be_payed!
      stage.save!
      # recomputing project's stat
      stage.project.reset_stat!
      stage.project.save!
    end
  end
end
